const express = require('express');
const api = require('../api/neteaseCloudMusicApi')
const {ApiResponse} = require("../model/response");
const cookieService = require("../service/cookie");
const router = express.Router();

// 热歌榜
router.get('/hot-song', (req, res) => {
    const {currentPage, pageSize} = req.query;
    const offset = (currentPage - 1) * pageSize;
    const limit = pageSize;
    api.getHotSong(limit, offset)
        .then(data => {
            const songs = data.songs;
            res.json(ApiResponse.ok(200, "成功", songs));
        })
        .catch(error => {
            console.log(error);
            res.json(ApiResponse.fail(500, "获取失败"));
        });
})


// 播放音乐
router.post('/song/play', async (req, res) => {
    const {musicId, musicName, publishTime, albumId, artistId, mvId, level, dt} = req.body;
    const music = {
        id: musicId,
        name: musicName,
        url: null,
        durationTime: dt,
        level: "standard",
        mvId: mvId,
        mvUrl: null,
        publishTime: publishTime,
        album: null,
        artist: null
    }
    // 获取音乐url
    try {
        const cookieRecord = await cookieService.getLastCookie();
        const songResult = await api.getSongUrl(musicId, level, cookieRecord.cookie);
        const song = songResult.data[0];
        music.id = song.id;
        music.url = song.url;
        music.level = song.level;
        music.durationTime = song.dt;
    } catch (e) {
        console.log(e)
    }
    // 获取歌手信息
    try {
        const artistResult = await api.getArtistInfo(artistId);
        const data = artistResult.data.artist;
        music.artist = {
            id: data.id,
            cover: data.cover,
            avatar: data.avatar,
            name: data.name,
            alias: data.alias,
            identities: data.identities,
            transNames: data.transNames,
            briefDesc: data.briefDesc,
            musicSize: data.musicSize,
            albumSize: data.albumSize,
            mvSize: data.mvSize,
        };
    } catch (e) {
        console.log(e)
    }
    // 获取专辑信息
    try {
        const albumResult = await api.getAlbumInfo(albumId)
        const data = albumResult.album;
        music.album = {
            id: data.id,
            publishTime: data.publishTime,
            size: data.size,
            picUrl: data.picUrl,
            blurPicUrl: data.blurPicUrl,
            description: data.description,
            name: data.name,
        };
    } catch (e) {
        console.log(e)
    }
    // 获取mv地址
    try {
        const mvResult = await api.getMvUrl(mvId);
        music.mvUrl = mvResult.data.url;
    } catch (e) {
        console.log(e)
    }
    res.json(ApiResponse.ok().sendData(music));
})


module.exports = router